<template>
  <view class="wrapper">
    <SearchBar @search="toSearchList" />
    <view class="history-search">
      <view class="title">
        <text class="title">历史搜索</text>
        <icon type="clear" size="18" @click="clearHistoryList"> </icon>
      </view>
      <view>
        <view
          v-for="(item, index) in keywordList"
          @click="toSearchList(item)" :key="index"
          >{{ item }}</view
        >
      </view>
    </view>
  </view>
</template>

<script>
import SearchBar from '../../components/SearchBar'

const KEYWORD_LIST = 'keyword_list'

export default {
  components: {
    SearchBar
  },
  data () {
    return {
      // 页面初始化时
      keywordList: []
    }
  },
  onShow () {
    // 页面初始化时，当搜索页面从其他页面返回时,把storage=>data.属性
    this.keywordList = wx.getStorageSync(KEYWORD_LIST) || []
  },
  methods: {
    // 清除历史列表
    clearHistoryList () {
      wx.showModal({
        title: '提示',
        content: '你确定要清除历史搜索吗？',
        success: res => {
          // 用户确认了
          if (res.confirm) {
            // 页面上更新
            this.keywordList = []
            // 清除存储
            wx.removeStorageSync(KEYWORD_LIST)
          }
        }
      })
    },
    // 跳转搜索列表页面,并按输入框的值进行搜索
    toSearchList (keyword) {
      // 关键字插入到头部,也可以使用unshift
      let _keywordList = [keyword, ...this.keywordList]
      // 去重
      _keywordList = [...new Set(_keywordList)]
      // 存储keywordList
      wx.setStorageSync(KEYWORD_LIST, _keywordList)
      wx.navigateTo({
        url: '/pages/search_list/main?catName=' + keyword
      })
    }
  }
}
</script>

<style lang="less">
.search {
  background-color: #eee;
  padding: 30rpx 15rpx;
  display: flex;
  justify-content: space-between;
  font-size: 28rpx;
  position: relative;

  icon {
    position: absolute;
    top: 50rpx;
    left: 38rpx;
  }

  input {
    height: 60rpx;
    flex: 1;
    background-color: #fff;
    padding-left: 70rpx;
    box-sizing: border-box;
    border-radius: 4rpx;
  }

  button {
    width: 160rpx;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
    border: 1rpx solid #bfbfbf;
    background-color: #eee;
    margin-left: 20rpx;
  }
}

.history-search {
  color: #333;
  font-size: 28rpx;
  padding: 30rpx 30rpx 30rpx 15rpx;

  .title {
    display: flex;
    justify-content: space-between;
  }

  view {
    display: flex;
    flex-wrap: wrap;
    margin-top: 30rpx;

    view {
      height: 64rpx;
      line-height: 64rpx;
      padding: 0 26rpx;
      background-color: #ddd;
      margin: 0 30rpx 16rpx 0;
    }
  }
}
</style>
